package com.yyb.aspectj; // 操作日志切面类所在包

import com.alibaba.fastjson2.JSON; // 用于对象转JSON字符串
import com.yyb.annotation.Log; // 自定义日志注解
import com.yyb.domain.SysOperLog; // 操作日志实体类
import com.yyb.domain.SysUser; // 系统用户实体类
import com.yyb.enums.StateEnums; // 状态枚举类
import com.yyb.exception.BusinessException; // 自定义业务异常
import com.yyb.sync.AsyncSysOperLogService; // 异步保存操作日志的服务
import com.yyb.utils.HttpUtils; // 获取IP地址工具类
import com.yyb.utils.SecurityUtils; // 获取当前用户工具类
import com.yyb.utils.ServletUtils; // 获取Request相关工具类
import jakarta.annotation.Resource; // 注入Bean用
import jakarta.servlet.http.HttpServletRequest; // 请求对象
import jakarta.servlet.http.HttpServletResponse; // 响应对象
import jakarta.servlet.http.HttpSession; // 会话对象
import lombok.extern.log4j.Log4j2; // 引入日志注解
import org.aspectj.lang.JoinPoint; // 切点对象
import org.aspectj.lang.annotation.AfterReturning; // 方法成功返回后通知
import org.aspectj.lang.annotation.AfterThrowing; // 方法抛出异常后通知
import org.aspectj.lang.annotation.Aspect; // 表示这是一个切面类
import org.aspectj.lang.annotation.Before; // 方法执行前通知
import org.springframework.beans.factory.annotation.Value; // 读取配置值
import org.springframework.context.annotation.EnableAspectJAutoProxy; // 启用AOP自动代理
import org.springframework.core.annotation.Order; // 指定切面优先级
import org.springframework.http.HttpMethod; // HTTP请求方法枚举
import org.springframework.stereotype.Component; // 注入容器
import org.springframework.util.StringUtils; // 字符串工具类
import org.springframework.validation.BindingResult; // Spring校验结果对象
import org.springframework.web.multipart.MultipartFile; // 上传文件对象
import org.springframework.web.servlet.HandlerMapping; // 请求映射处理器

import java.util.Collection;
import java.util.Date;
import java.util.Map;

/**
 * 操作日志的切面类，拦截带有@Log注解的方法并记录日志
 */
@Component // 注册为Spring组件
@Aspect // 声明为切面类
@Order(-1) // 优先级高于事务切面
@EnableAspectJAutoProxy // 启用AOP代理
@Log4j2 // 开启日志功能
public class LogAspect {

    @Value("${spring.profiles.active}") // 读取当前环境配置
    private String profile;

    @Resource // 注入异步日志保存服务
    private AsyncSysOperLogService sysOperLogService;

    /**
     * 方法执行成功后调用
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        if(profile.equals("dev")){
            throw new BusinessException("当前显演示环境，不支持添加修改删除");
        }
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 方法抛出异常后调用
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    /**
     * 统一处理日志的主方法
     */
    private void handleLog(JoinPoint joinPoint, Log controllerLog, Exception e, Object jsonResult) {
        try {
            SysUser loginUser = SecurityUtils.getCurrentUser(); // 获取当前用户
            SysOperLog operLog = new SysOperLog(); // 创建日志对象
            operLog.setOperTime(new Date()); // 设置操作时间
            operLog.setStatus(StateEnums.REQUEST_SUCCESS.getCode()); // 默认设置成功
            operLog.setOperIp(HttpUtils.getIpAddr(ServletUtils.getRequest())); // 设置IP
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); // 设置URL
            if (loginUser != null) {
                operLog.setUserId(loginUser.getUserId());
                operLog.setOperName(loginUser.getUserName());
            }
            if (e != null) {
                operLog.setStatus(StateEnums.REQUEST_ERROR.getCode());
                String message = e.getMessage();
                operLog.setErrorMsg(message.length() > 2000 ? message.substring(0, 2000) : message);
            }
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()"); // 设置方法名
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod()); // 设置请求类型
            getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult); // 解析注解
            sysOperLogService.saveOperLog(operLog); // 异步保存日志
        } catch (Exception error) {
            log.error("操作日志切面出现异常:{}", error.getMessage());
        }
    }

    /**
     * 从注解中获取模块名、操作类型等
     */
    private void getControllerMethodDescription(JoinPoint joinPoint, Log controllerLog, SysOperLog operLog, Object jsonResult) throws Exception {
        operLog.setTitle(controllerLog.title());
        operLog.setBusinessType(controllerLog.businessType().getCode());

        if (controllerLog.isSaveRequestData()) {
            setRequestValue(joinPoint, operLog); // 保存请求参数
        }
        if (controllerLog.isSaveResponseData() && jsonResult != null) {
            String result = JSON.toJSONString(jsonResult);
            if (result.length() > 2000) {
                result = result.substring(0, 2000);
            }
            operLog.setJsonResult(result); // 保存响应结果
        }
    }

    /**
     * 获取请求参数（POST、PUT）或URL参数
     */
    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception {
        String requestMethod = operLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            if (params.length() > 2000) {
                params = params.substring(0, 2000);
            }
            operLog.setOperParam(params);
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            String params = paramsMap != null ? paramsMap.toString() : null;
            if (params != null && params.length() > 2000) {
                params = params.substring(0, 2000);
            }
            operLog.setOperParam(params);
        }
    }

    /**
     * 拼接参数转JSON字符串
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        for (Object o : paramsArray) {
            if (o != null && !isFilterObject(o)) {
                try {
                    String jsonObj = JSON.toJSONString(o);
                    params.append(jsonObj).append(" ");
                } catch (Exception ignored) {
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断参数是否为需要过滤的类型（如文件、请求、响应）
     */
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            for (Object value : (Collection<?>) o) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            for (Object value : ((Map<?, ?>) o).entrySet()) {
                return ((Map.Entry<?, ?>) value).getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult || o instanceof HttpSession;
    }

}
